package one.stand.controller;

import com.jmp.api.user.dto.LiveListRequest;
import com.jmp.api.user.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.LiveInfoRequest;
import com.jmp.base.dto.LiveInfoResponse;
import com.jmp.base.dto.*;
import com.jmp.feign.AccountFeign;
import com.jmp.feign.LiveFeign;
import com.jmp.feign.RecordFeign;
import com.jmp.feign.TemplateFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.Company2Dto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.enums.LoginEnum;
import one.stand.enums.SeeRecordEnums;
import one.stand.model.BusinessCard;
import one.stand.model.Company;
import one.stand.model.Goods;
import one.stand.model.ResultModel;
import one.stand.service.*;
import one.stand.service.sys.SysDictValueService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.List;

@Api(description = "直播:创建直播|开播|直播间")
@RestController
@RequestMapping("userApi/live")
public class LiveController {
    public static SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    @Autowired
    private LiveFeign liveFeign;
    @Autowired
    private RecordFeign recordFeign;
    @Autowired
    private TemplateFeign templateFeign;
    @Autowired
    private AccountFeign accountFeign;

    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private SysDictValueService sysDictValueService;

    @ApiOperation(value = "直播信息")
    @PostMapping("info")
    @SecurityAuthCheck
    public ResultModel<com.jmp.api.user.dto.LiveInfoResponse> info(@RequestAttribute com.jmp.api.user.dto.LiveInfoRequest request) {
        boolean isOn = sysDictValueService.isOn(SysDictValueService.Type.LIVE_OPEN, String.valueOf(request.getCardId()));

        com.jmp.api.user.dto.LiveInfoResponse response = com.jmp.api.user.dto.LiveInfoResponse.builder()
                .open(BooleanUtils.toInteger(isOn))
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "直播大厅")
    @PostMapping("list")
    @SecurityAuthCheck
    public ResultModel<LiveListResponse> list(@RequestAttribute LiveListRequest request) {

        BusinessCard card = businessCardBaseService.getCustomer(request.getCardId());
        AssertUtil.nonNull(card, ResultEnum.PARAM_CHECK, "名片不存在");

        com.jmp.base.dto.LiveListRequest liveListRequest = com.jmp.base.dto.LiveListRequest.builder()
                .companyId(card.getCompanyId())
                .build();
        liveListRequest.setPageNum(request.getPageNum());
        liveListRequest.setPageSize(request.getPageSize());
        ResultModel<LiveListVo> liveListVoResultModel = liveFeign.list(liveListRequest);
        AssertUtil.isTrue(liveListVoResultModel);
        PageResponse2<LiveListResponse.Live> livePage = ConvertUtils.page2(liveListVoResultModel.getData().getLivePage(), live -> {
            BusinessCard businessCard = businessCardBaseService.getCustomer(live.getCardId());
            Company company = companyBaseService.getById(businessCard.getCompanyId());
            return LiveListResponse.Live.builder()
                    .roomId(live.getRoomId())
                    .photo(live.getPhoto())
                    .status(getStatus(live.getStatus()))
                    .viewNum(live.getStatus() == 1 ? live.getViewNum() + "人观看" : StringUtils.EMPTY)//直播中才显示观看人数
                    .userImg(company.getCompanyLogo())
                    .userName(company.getCompanyName())
                    .build();
        });

        LiveListResponse response = LiveListResponse.builder()
                .livePage(livePage)
                .status(0)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "直播间-观看直播")
    @PostMapping("view")
    @SecurityAuthCheck
    public ResultModel<LiveViewApiResponse> view(@RequestAttribute LiveViewApiRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<LiveInfoResponse> infoResponseResultModel = liveFeign.info(LiveInfoRequest.builder()
                .roomId(request.getRoomId())
                .build());
        AssertUtil.isTrue(infoResponseResultModel);
        LiveInfoResponse infoResponse = infoResponseResultModel.getData();
        AssertUtil.isTrue(infoResponse.isHasRoom(), ResultEnum.PARAM_CHECK, "直播已取消");

        BusinessCard businessCard = businessCardBaseService.getCustomer(infoResponse.getCardId());
        Company2Dto company = companyBaseService.get2(businessCard.getCompanyId());
        final boolean hasZkgx = companyBaseService.hasZkgx(businessCard.getCompanyId());

        LiveViewApiResponse response = null;
        if (infoResponse.isPre()) {
            boolean preFollow = recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_LIVE_ROOM_PRE, request.getRoomId());
            response = LiveViewApiResponse.builder()
                    .status(2)
                    .name(infoResponse.getName())
                    .photo(infoResponse.getPhoto())
                    .preTime(DateUtil.format(formatter, infoResponse.getPreTime()))
                    .remainingTime(infoResponse.countRemainingTime())
                    .preFollow(BooleanUtils.toInteger(preFollow))
                    .build();
        } else if (infoResponse.isOn()) {
            response = LiveViewApiResponse.builder()
                    .companyName(company.getCompanyName())
                    .companyLogo(company.getCompanyLogo())
                    .companyLevel(company.countCompanyLevelView())
                    .hasZkgx(BooleanUtils.toInteger(hasZkgx))
                    .viewerNum(infoResponse.getViewerNum())
                    .viewerPhotos(infoResponse.getViewerPhotos())
                    .status(0)
                    .pullUrl(infoResponse.getPullUrl().replaceAll(".flv", ".m3u8"))
                    .groupId(infoResponse.getGroupId())
                    .build();
        } else if (infoResponse.isReview()) {
            response = LiveViewApiResponse.builder()
                    .companyName(company.getCompanyName())
                    .companyLogo(company.getCompanyLogo())
                    .companyLevel(company.countCompanyLevelView())
                    .hasZkgx(BooleanUtils.toInteger(hasZkgx))
                    .viewerNum(infoResponse.getViewerNum())
                    .viewerPhotos(infoResponse.getViewerPhotos())
                    .status(1)
                    .videoUrl(infoResponse.getVideoUrl())
                    .build();
        } else {
            AssertUtil.fail(ResultEnum.PARAM_CHECK, "直播已取消");
        }

        response.setCompanyId(businessCard.getCompanyId());
        boolean isCollection = recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_COMPANY, businessCard.getCompanyId());
        response.setFollowFlag(BooleanUtils.toInteger(isCollection));
        boolean isThumbs = recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_LIVE_ROOM, request.getRoomId());
        response.setThumbsFlag(BooleanUtils.toInteger(isThumbs));

        if (!RequestContextHolder.getRequestContext().isSelf(businessCard.getUserId())) {//不是同一用户
            recordPublicService.addPopularity(SeeRecordEnums.LIVE, request.getRoomId());
        }

        return ResultModel.success(response);
    }

    @ApiOperation(value = "直播间-商品列表")
    @PostMapping("goods")
    @SecurityAuthCheck
    public ResultModel<LiveGoodsApiResponse> goods(@RequestAttribute LiveGoodsApiRequest request) {
        LiveGoodsListRequest goodsListRequest = LiveGoodsListRequest.builder()
                .roomId(request.getRoomId())
                .status(1)
                .build();
        ResultModel<LiveGoodsListResponse> infoResponseResultModel = liveFeign.goodsList(goodsListRequest);
        AssertUtil.isTrue(infoResponseResultModel);
        List<LiveGoodsListResponse.Goods> selectGoodsIds = infoResponseResultModel.getData().getGoodsIds();
        List<LiveGoodsApiResponse.Goods> goodsPageResponse2 = ConvertUtils.list(selectGoodsIds, goodsId -> {
            Goods goods = goodsBaseService.get(goodsId.getGoodsId());

            return LiveGoodsApiResponse.Goods.builder()
                    .roomGoodsId(goodsId.getRoomGoodsId())
                    .goodsId(goodsId.getGoodsId())
                    .name(goods.getGoodsName())
                    .photo(goodsPhotoService.getPath(goodsId.getGoodsId()))
                    .price(goods.getPrice())
                    .status(goodsId.getStatus())
                    .build();
        });

        LiveGoodsApiResponse response = LiveGoodsApiResponse.builder()
                .goodsList(goodsPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "直播间-关注")
    @PostMapping("follow")
    @SecurityAuthCheck
    public ResultModel follow(@RequestAttribute LiveFollowRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<RecordCollectionVo> resultModel = recordFeign.collection(RecordCollectionDto.builder()
                .userId(optUser.getUserId())
                .itemType(RecordPublicService.ITEMTYPE_COMPANY)
                .itemId(request.getCompanyId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "直播间-点赞")
    @PostMapping("thumbs")
    @SecurityAuthCheck
    public ResultModel thumbs(@RequestAttribute LiveThumbsRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<RecordCollectionVo> resultModel = recordFeign.collection(RecordCollectionDto.builder()
                .userId(optUser.getUserId())
                .itemType(RecordPublicService.ITEMTYPE_LIVE_ROOM)
                .itemId(request.getRoomId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "直播间-分享")
    @PostMapping("/share")
    @SecurityAuthCheck
    public ResultModel<LiveShareResponse> share(@RequestAttribute LiveShareRequest request) {

//        RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<LiveInfoResponse> infoResponseResultModel = liveFeign.info(LiveInfoRequest.builder()
                .roomId(request.getRoomId())
                .build());
        AssertUtil.isTrue(infoResponseResultModel);
        LiveInfoResponse infoResponse = infoResponseResultModel.getData();
        AssertUtil.isTrue(infoResponse.isHasRoom(), ResultEnum.PARAM_CHECK, "直播已取消");

        TemplateGet2Request getRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_ROOM)
                .cardId(infoResponse.getCardId())
                .roomId(request.getRoomId())
                .build();
        ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(getRequest);
        AssertUtil.isTrue(getResponseResultModel);
        String cardUrl = getResponseResultModel.getData().getImageUrl();

        BusinessCard card = businessCardBaseService.getCustomer(infoResponse.getCardId());
        AccountCompanyIdRequest accountCompanyIdRequest = AccountCompanyIdRequest.builder()
                .companyId(card.getCompanyId())
                .loginEnum(LoginEnum.USER)
                .build();
        ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyIdDefaultIfNull(accountCompanyIdRequest);
        String wechatId = accountResponseResultModel.isSuccess() ? accountResponseResultModel.getData().getWechatId() : null;

        LiveShareResponse response = LiveShareResponse.builder()
                .cardUrl(cardUrl)
                .wechatId(wechatId)
                .title(infoResponse.getName())
                .photo(infoResponse.getPhoto())
                .path(recordPublicService.getLiveRoomWxUrl(request.getRoomId()))
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3直播间:预约关注")
    @PostMapping("pre/follow")
    @SecurityAuthCheck
    public ResultModel preFollow(@RequestAttribute LivePreFollowRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<RecordCollectionVo> resultModel = recordFeign.collection(RecordCollectionDto.builder()
                .userId(optUser.getUserId())
                .itemType(RecordPublicService.ITEMTYPE_LIVE_ROOM_PRE)
                .itemId(request.getRoomId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    private String getStatus(Integer status) {
        if (status == 0) {
            return "https://file.hongmushichang.com/0/mp/room/yugao.png";
        } else if (status == 1) {
            return "https://file.hongmushichang.com/0/mp/room/zhibozhong.png";
        } else if (status == 2) {
            return "https://file.hongmushichang.com/0/mp/room/hf.png";
        }
        return null;
    }
}
